<template>
  <div class="page-container fixed-bottom">
    <div class="tabs-box">
      <el-tabs v-model="shopIndex" type="card" editable @tab-click="selectTab" @edit="handleTabsEdit">
        <el-tab-pane
          v-for="(item, index) in formList"
          :key="index"
          :label="`项目${index + 1}`"
          :name="index.toString()"
        />
      </el-tabs>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="项目名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="项目简介：" prop="introduction">
        <el-input v-model="form.introduction" type="textarea" rows="5" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="项目开放时间：" prop="dateRuleDesc">
        <el-input v-model="form.dateRuleDesc" type="textarea" rows="5" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="是否可见：" prop="isVisible">
        <el-select v-model="form.isVisible" placeholder="请选择" clearable>
          <el-option :value="0" label="不可见" />
          <el-option :value="1" label="可见" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否收费：" prop="isFee">
        <el-select v-model="form.isFee" placeholder="请选择" clearable>
          <el-option :value="0" label="免费项目" />
          <el-option :value="1" label="收费项目" />
          <el-option :value="2" label="线下购" />
        </el-select>
      </el-form-item>

      <el-form-item label="项目图片：" prop="imgUrls">
        <UploadFile :file-list="form.imgUrls" :limit="6" @change="uploadHandle($event, 'imgUrls','imgUrls')">
          <div slot="tip">
            <p>建议尺寸：封面690*350px，首图/详情图690*350px，小于1M的JPG/PNG/GIF格式的图片</p>
          </div>
        </UploadFile>
      </el-form-item>
      <el-form-item label="项目详情：" prop="details">
        <RichText :value.sync="form.details" />
      </el-form-item>
    </el-form>
    <div class="bottom-handle-box">
      <el-button v-if="!form.id" @click="confirmHandle(true)">保存草稿</el-button>
      <el-button type="primary" @click="confirmHandle(false)">发布</el-button>
    </div>
  </div>
</template>

<script>

import { createShopProject, getShopProjectList, deleteShopProject, getShopDraft } from '@/api/shop'
import UploadFile from '@/components/UploadFile/index.vue'
import RichText from '@/components/RichText/index.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'Recommend',
  components: {
    UploadFile,
    RichText
  },
  data() {
    return {
      shopId: '',
      shopIndex: '0',
      form: {},
      formItem: {
        name: '',
        introduction: '',
        dateRuleDesc: '',
        isVisible: '',
        isFee: '',
        imgUrls: '',
        details: ''
      },
      formList: [],
      rules: {
        name: [
          { required: true, message: '请输入项目名称', trigger: ['blur'] }
        ],
        introduction: [
          { required: true, message: '请输入项目简介', trigger: ['blur'] }
        ],

        dateRuleDesc: [
          { required: true, message: '请输入项目开放时间', trigger: ['blur'] }
        ],
        isVisible: [
          { required: true, message: '请选择是否可见', trigger: ['change'] }
        ],
        isFee: [
          { required: true, message: '请选择是否免费', trigger: ['change'] }
        ],
        imgUrls: [
          { required: true, message: '请上传项目图片', trigger: ['change'] }
        ],
        details: [
          { required: true, message: '请输入项目详情', trigger: ['change'] }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'currentEnterprise',
      'currentSite'
    ])
  },

  created() {
    this.getShopDraft()
  },

  methods: {

    // 获取店铺装修草稿
    getShopDraft() {
      const data = {
        siteId: this.currentSite.id
      }
      getShopDraft(data).then(res => {
        this.shopId = res?.id
        this.getShopProject(false)
      }).catch(() => {})
    },

    // 获取已发布数据或者草稿数据
    getShopProject(draft) {
      const data = {
        siteId: this.currentSite.id,
        draft
      }
      getShopProjectList(data).then(res => {
        if (res?.length === 0) {
          if (draft) {
            this.formList.push({ ...this.formItem })
            this.form = this.formList[0]
          } else {
            // 如果没有已发布数据，再请求已保存草稿数据
            this.getShopProject(true)
          }
        } else {
          this.formList = res
          this.form = this.formList[0]
        }
        setTimeout(() => {
          this.$refs.form.clearValidate()
        }, 0)
      }).catch(() => {})
    },

    // 编辑tabs
    handleTabsEdit(targetName, action) {
      targetName = Number(targetName)
      if (action === 'add') {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.formList.push({ ...this.formItem })
            this.shopIndex = (this.formList.length - 1).toString()
            this.form = this.formList[this.shopIndex]
          } else {
            return false
          }
        })
      }
      if (action === 'remove') {
        if (this.formList.length === 1) {
          return false
        }
        this.$confirm('确定删除该项目吗?', '提示', {
          type: 'warning' }).then(() => {
          const data = {
            id: this.formList[targetName].id
          }
          deleteShopProject(data).then(() => {
            this.shopIndex = '0'
            this.formList = this.formList.filter((item, index) => index !== targetName)
            this.form = this.formList[0]
          }).catch(() => {})
        }).catch(() => {})
      }
    },

    // 选择tab
    selectTab(tab) {
      this.shopIndex = tab.index
      this.form = this.formList[this.shopIndex]
      this.$refs.form.clearValidate()
    },

    // 上传图片处理
    uploadHandle(payload, name, prop) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form[name] = result.join(',')
      this.$refs.form.validateField(prop)
    },

    // 保存
    async confirmHandle(draft) {
      if (!draft) {
        await this.$refs.form.validate()
      }
      const data = {
        ...this.form,
        productType: 0,
        draft,
        enterpriseId: this.currentEnterprise.id,
        siteId: this.currentSite.id,
        shopId: this.shopId
      }
      createShopProject(data).then(() => {
        if (draft) {
          this.$message.success('保存草稿成功')
        } else {
          this.$message.success('发布成功')
          this.status = -1
        }
      }).catch(() => {})
    }

  }
}
</script>

<style lang="scss" scoped></style>
